

# K个一组翻转链表



class ListNode:

    def __init__(self, val=0, next=None):

        self.val = val
        self.next = next
    

class Solution:

    def reverseKGroup(self, head, k):
        
        # if not (head and head.next):
        #     return head

        # p = ListNode(-1)

        # heads, stack = p, [] 
        
        # while head and head.next:
        #     temp = head
        #     for _ in range(k):
        #         stack.append(head)
        #         head = head.next
            
        #     if len(stack) < k:
        #         p.next = temp
        #         return heads.next
            
        #     while stack:
        #         p.next = stack.pop()
        #         p = p.next
            
        # return heads.next

        # =========超时=========


        # 统计节点的个数
        n = 0
        cur = head
        while cur:
            n += 1
            cur = cur.next
        
        p0 = dummy = ListNode(next=head)
        pre = None
        cur = head
        while n >= k:
            n -= k

            for _ in range(k):

                nxt = cur.next # 暂存后面的节点
                cur.next = pre # 进行翻转
                pre = cur # 更新
                cur = nxt # 恢复后序

            # 翻转后
            nxt = p0.next # 保存当前组反转前的第一个节点 nxt 反转后从头变成了尾巴，自然尾巴接下一组
            nxt.next = cur # 将反转后的最后一个节点连接到下一组
            p0.next = pre # 将上一组连接到当前组反转后的第一个节点
            p0 = nxt # 更新p0为当前组的最后一个节点，为下次反转做准备
        
        return dummy.next







